using System.Configuration;
using System.IO;
using System.Xml.Serialization;
using Cfg.ConfigProviders.DotNet.Xml;

namespace Cfg.ConfigProviders
{
    public class DotnetConfigFileProvider : ConfigFileProviderBase
    {
        private readonly string[] _variablePatterns = { "(%[^%]*%)" };

        public override string[] VariablePatterns
        {
            get { return _variablePatterns; }
        }

        public DotnetConfigFileProvider(string path) : base(path)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ConfigKeyValues GetValues()
        {
            if (string.IsNullOrEmpty(Path))
            {
                foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                {
                    Values[key] = ConfigurationManager.AppSettings[key];
                }
                return Values;
            }

            DotNetConfigFile config;
            var serializer = new XmlSerializer(typeof(DotNetConfigFile));
            using (var fs = File.OpenRead(Path))
            {
                config = (DotNetConfigFile)serializer.Deserialize(fs);
            }

            foreach (var keyValuePair in config.KeyValuePairs)
            {
                Values[keyValuePair.Key] = keyValuePair.Value;
            }

            return Values;
        }
    }
}